import { request } from '@/utils/request'

// 竞赛相关类型定义
export interface Contest {
  id: number
  title: string
  description?: string
  type: 'individual' | 'team'
  status: 'upcoming' | 'running' | 'ended'
  start_time: string
  end_time: string
  duration: number
  max_participants?: number
  author_id: number
  rules?: string
  participant_count: number
  is_public: boolean
  created_at: string
  updated_at: string
  author?: {
    id: number
    username: string
    avatar?: string
  }
  questions?: any[]
}

export interface ContestParticipant {
  id: number
  contest_id: number
  user_id: number
  team_name?: string
  total_score: number
  solved_count: number
  penalty_time: number
  rank?: number
  last_submission_time?: string
  joined_at: string
  user?: {
    id: number
    username: string
    avatar?: string
  }
}

export interface ContestRanking {
  contest: Contest
  participants: ContestParticipant[]
  total: number
  page: number
  page_size: number
}

export interface RecentContestRanking {
  contest: Contest
  top_rankings: ContestParticipant[]
}

// 获取竞赛列表
export const getContests = (params?: {
  status?: string
  type?: string
  search?: string
  page?: number
  page_size?: number
}) => {
  return request.get<{
    contests: Contest[]
    total: number
    page: number
    page_size: number
  }>('/v1/contests', { params })
}

// 获取即将开始的竞赛
export const getUpcomingContests = () => {
  return request.get<Contest[]>('/v1/contests/upcoming')
}

// 获取当前竞赛
export const getCurrentContest = () => {
  return request.get<Contest | null>('/v1/contests/current')
}

// 获取竞赛详情
export const getContest = (id: number) => {
  return request.get<Contest>(`/v1/contests/${id}`)
}

// 获取竞赛排行榜
export const getContestRanking = (id: number, params?: {
  page?: number
  page_size?: number
}) => {
  return request.get<ContestRanking>(`/v1/contests/${id}/ranking`, { params })
}

// 获取最近竞赛排行榜
export const getRecentContestRankings = () => {
  return request.get<RecentContestRanking[]>('/v1/contests/recent-rankings')
}

// 加入竞赛
export const joinContest = (id: number) => {
  return request.post<{ message: string }>(`/v1/contests/${id}/join`)
}

// 获取用户竞赛历史
export const getUserContestHistory = () => {
  return request.get<ContestParticipant[]>('/v1/contests/my-history')
}
